package com.mhs.tracuu;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import org.ksoap2.serialization.SoapObject;

import com.mhs.BUS.ThuocBUS;
import com.mhs.DTO.MySQLiteHelper;
import com.mhs.DTO.ThuocDTO;
import com.mhs.mydialog.MyDialogListner;
import com.mhs.services.ServiceSearch;

import com.mhs.mhs_gui.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class CopyOfTraCuuThuoc_Search extends Activity
{
	private Runnable viewOrders;
	private ProgressDialog m_ProgressDialog = null;

	MySQLiteHelper dbHelper;
	public final Context THIS = this;
	private String s_loaithuoc = "";
	ListView myList;
	Spinner spinSearchType;
	EditText editTextSearch;
	
	ArrayAdapter<String> aa_adapter;
	ArrayList<String> lstTenThuoc;
	
	static public String sTypeSearch = "";
	static public String keyWord = "";
	static public ThuocDTO[] lstThuocDTO = null;

	private OnClickListener showDialog = new OnClickListener() 
	{
		public void onClick(View v) 
		{
			final Dialog dialog = new Dialog(CopyOfTraCuuThuoc_Search.this);
			dialog.setCancelable(true);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.status_dialog);

			Button btnCancel = (Button) dialog.findViewById(R.id.cancel_choose_status);
			btnCancel.setOnClickListener(new OnClickListener() 
			{
				public void onClick(View v) 
				{
					dialog.cancel();
				}
			});

			RadioGroup rgStatus = (RadioGroup)dialog.findViewById(R.id.radioGroup1);
			rgStatus.setOnCheckedChangeListener(new OnCheckedChangeListener() 
			{
				public void onCheckedChanged(RadioGroup group, int checkedId) 
				{
					switch (checkedId) 
					{
					case R.id.rd_tenthuoc:
						s_loaithuoc = "Tên thuốc";
						dialog.cancel();
						break;
					case R.id.rd_thanhphan:
						s_loaithuoc = "Thành phần";
						dialog.cancel();
						break;
					case R.id.rd_chidinh:
						s_loaithuoc = "Chỉ định";
						dialog.cancel();
						break;
					case R.id.rd_sodangky:
						s_loaithuoc = "Số đăng ký";
						dialog.cancel();
						break;
					case R.id.rd_congtysanxuat:
						s_loaithuoc = "Công ty sản xuất";
						dialog.cancel();
						break;
					default:
						break;
					}

					//TextView tv_temp = (TextView)findViewById(R.id.tv_loaitimkiem);
					//tv_temp.setText(s_loaithuoc);
					Toast.makeText(CopyOfTraCuuThuoc_Search.this, s_loaithuoc, Toast.LENGTH_SHORT).show();
				}
			});
			dialog.show();
		}

		//ở đây m cho nó load lên luôn đi, lát nữa t move qua bê kia





	};

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tracuuthuoc_search);

		lstTenThuoc = new ArrayList<String>();
		aa_adapter = new ArrayAdapter<String>(this, R.layout.listview_item, lstTenThuoc);
		
		editTextSearch = (EditText)findViewById(R.id.et_keyword);
		spinSearchType = (Spinner)findViewById(R.id.s_spinnerTypeSearch);
		myList = (ListView)findViewById(R.id.lv_thuocvuaxem);

		ImageView iv_submitSearch = (ImageView)findViewById(R.id.iv_submitSearch);
		iv_submitSearch.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v) 
			{
				CheckBox cb_internet  = (CheckBox)findViewById(R.id.cb_internet);
				if(!cb_internet.isChecked())
					SubmitSearch_Cache(v);
				else
					SubmitSearch_Internet(v);

			}
		});

		//Spinner loại tìm kiếm
		Spinner spinner = (Spinner) findViewById(R.id.s_spinnerTypeSearch);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.typesearchArray, R.layout.my_spinner);
		adapter.setDropDownViewResource(R.layout.my_spinner_dropdown_item);
		spinner.setAdapter(adapter); 


		CheckBox cb_internet = (CheckBox)findViewById(R.id.cb_internet);
		cb_internet.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v) 
			{
				CheckBox cb_internet  = (CheckBox)findViewById(R.id.cb_internet);
				CheckBox cb_cache  = (CheckBox)findViewById(R.id.cb_cache);
				if(!cb_internet.isChecked())
				{
					if(!cb_cache.isChecked())
					{
						cb_cache.setChecked(true);
					}
					//ImageView iv_submitSearch = (ImageView)findViewById(R.id.iv_submitSearch);
					//iv_submitSearch.setVisibility(View.INVISIBLE);					
				}
				else
				{
					//ImageView iv_submitSearch = (ImageView)findViewById(R.id.iv_submitSearch);
					//iv_submitSearch.setVisibility(View.VISIBLE);
				}
			}
		});

		CheckBox cb_cache = (CheckBox)findViewById(R.id.cb_cache);
		cb_cache.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v) 
			{
				CheckBox cb_internet  = (CheckBox)findViewById(R.id.cb_cache);
				CheckBox cb_cache  = (CheckBox)findViewById(R.id.cb_cache);
				if(!cb_internet.isChecked() && !cb_cache.isChecked())
				{
					cb_cache.setChecked(true);
				}
				else
				{
					cb_cache.setChecked(false);
				}
			}
		});

		//		ExpandableListView listView = (ExpandableListView) findViewById(R.id.elv_loaitimkiem);
		//		fakeData();
		//		listView.setAdapter(adapter);
		//		listView.setOnChildClickListener(new OnChildClickListener() 
		//		{
		//			public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) {
		//				
		//				Item aa = (Item)adapter.getChild(groupPosition, childPosition);
		//				
		//				TextView tv_temp = (TextView)findViewById(R.id.tv_loaitimkiem);
		//				tv_temp.setText(aa.getName());
		//				
		//				return false;
		//			}
		//		});
		//		listView.setOnGroupClickListener(new OnGroupClickListener() 
		//		{
		//			public boolean onGroupClick(ExpandableListView parent, View view, int groupPosition, long id) 
		//			{
		//				return false;
		//			}
		//		});
	}


	protected void SubmitSearch_Cache(View v) 
	{
		switch (v.getId()) 
		{
		case R.id.iv_submitSearch:
			String keyWord = editTextSearch.getText().toString();
			int typeSearch = Integer.valueOf((int)spinSearchType.getSelectedItemId());

			if(keyWord.isEmpty())
			{
				// keyWor is Empty
				MyDialogListner.ShowMessageAlert(this, "Chưa nhập keyword tìm kiếm!");
			}
			else
			{
				ThuocBUS thuocBUS = new ThuocBUS();
				List<ThuocDTO> lstThuoc = thuocBUS.timKiemThuocBUS(keyWord, typeSearch, this);

				if(lstThuoc.size() == 0)
				{

					MyDialogListner.ShowMessageAlert(this, "Không tìm thấy kết quả");	
				}
				else
				{
					// Show lstThuoc to listView		
					showSearchResultToListView(lstThuoc);
				}
			}
			break;
		}

	}

	protected void SubmitSearch_Internet(View v) 
	{
		switch (v.getId()) 
		{
		case R.id.iv_submitSearch:
			keyWord = editTextSearch.getText().toString();
			int typeSearch = Integer.valueOf((int)spinSearchType.getSelectedItemId());

			if(keyWord.isEmpty())
			{
				// keyWor is Empty
				MyDialogListner.ShowMessageAlert(this, "Chưa nhập keyword tìm kiếm!");
			}
			else
			{
				ThuocBUS thuocBUS = new ThuocBUS();

				switch(typeSearch)
				{
				case 0: // tenthuoc
					sTypeSearch  = "tenthuoc";
					break;
				case 1: // thanhphan
					sTypeSearch = "thanhphan";
					break;
				case 2: // chidinh
					sTypeSearch = "chidinh";
					break;
				case 3: // congtysanxuat
					sTypeSearch = "congtysanxuat";
					break;
				case 4: // sodangky
					sTypeSearch = "sodangky";
					break;
				default:
					break;
				}
				// Send query to server and wait result from server


				viewOrders = new Runnable()
				{
					public void run() 
					{
						// Chỗ này g�?i hàm này để chạy, sau khi chạy v�? thì thôg báo kết quả
						getResponseFromService();
						runOnUiThread(returnRes);
					}
				};
				Thread thread =  new Thread(null, viewOrders, "MagentoBackground");
				thread.start();
				m_ProgressDialog = ProgressDialog.show(CopyOfTraCuuThuoc_Search.this, "Please wait...", "Retrieving data ...", true);
			}
			break;
		}
	}
	
	private Runnable returnRes = new Runnable() 
	{
		public void run() 
		{
			if(lstThuocDTO.length ==  0)
			{
				MyDialogListner.ShowMessageAlert(THIS, "Không tìm thấy kết quả");	
			}
			else
			{
				//showSearchResultToListView(lstThuocDTO);
				for(int i = 0; i < lstThuocDTO.length; i++)
				{
					ThuocDTO thuoc = lstThuocDTO[i];
					lstTenThuoc.add(thuoc.getTENTHUOC());
				}
				String[] tenThuocs = lstTenThuoc.toArray(new String[0]);
				
				aa_adapter.notifyDataSetChanged();
			}
			m_ProgressDialog.dismiss();
		}
	};

	public void getResponseFromService()
	{
		SoapObject response = ServiceSearch.InvokeMethod(keyWord, sTypeSearch);
		// check response is null
		if(response != null)
		{
			lstThuocDTO = RetrieveFromSoap(response);
		}
		else
		{
			lstThuocDTO = null;
		}
	}

	public ThuocDTO[] RetrieveFromSoap(SoapObject response)
	{
		ThuocDTO[] lstThuoc = new ThuocDTO[response.getPropertyCount()];
		for (int i = 0; i < lstThuoc.length; ++i){
			SoapObject soTemp = (SoapObject)response.getProperty(i);
			ThuocDTO thuocDTO = new ThuocDTO();
			String sChoCapNhat = "Ch�? cập nhật";

			thuocDTO.setMATHUOC(Integer.parseInt(soTemp.getProperty(0).toString()));
			thuocDTO.setMALOAITHUOC(Integer.parseInt(soTemp.getProperty(1).toString()));
			thuocDTO.setHINHANH(soTemp.getProperty(2).toString());
			thuocDTO.setTENTHUOC(soTemp.getProperty(3).toString());
			thuocDTO.setSODANGKY(soTemp.getProperty(4).toString());

			if(soTemp.getProperty(5).toString().equals("anyType{}")){
				thuocDTO.setTHANHPHAN(sChoCapNhat);
			}else{
				thuocDTO.setTHANHPHAN(soTemp.getProperty(5).toString());
			}
			if(soTemp.getProperty(6).toString().equals("anyType{}")){
				thuocDTO.setDANGBAOCHE(sChoCapNhat);
			}else{
				thuocDTO.setDANGBAOCHE(soTemp.getProperty(6).toString());
			}
			if(soTemp.getProperty(7).toString().equals("anyType{}")){
				thuocDTO.setDONGGOI(sChoCapNhat);
			}else{
				thuocDTO.setDONGGOI(soTemp.getProperty(7).toString());
			}
			if(soTemp.getProperty(8).toString().equals("anyType{}")){
				thuocDTO.setCONGTYSANXUAT(sChoCapNhat);
			}else{
				thuocDTO.setCONGTYSANXUAT(soTemp.getProperty(8).toString());
			}
			if(soTemp.getProperty(9).toString().equals("anyType{}")){
				thuocDTO.setCHIDINH(sChoCapNhat);
			}else{
				thuocDTO.setCHIDINH(soTemp.getProperty(9).toString());
			}
			if(soTemp.getProperty(10).toString().equals("anyType{}")){
				thuocDTO.setCHONGCHIDINH(sChoCapNhat);
			}else{
				thuocDTO.setCHONGCHIDINH(soTemp.getProperty(10).toString());
			}
			if(soTemp.getProperty(11).toString().equals("anyType{}")){
				thuocDTO.setTUONGTACTHUOC(sChoCapNhat);
			}else{
				thuocDTO.setTUONGTACTHUOC(soTemp.getProperty(11).toString());	
			}
			if(soTemp.getProperty(12).toString().equals("anyType{}")){
				thuocDTO.setCHUYDEPHONG(sChoCapNhat);
			}else{
				thuocDTO.setCHUYDEPHONG(soTemp.getProperty(12).toString());
			}
			if(soTemp.getProperty(13).toString().equals("anyType{}")){
				thuocDTO.setTACDUNGPHU(sChoCapNhat);
			}else{
				thuocDTO.setTACDUNGPHU(soTemp.getProperty(13).toString());
			}
			if(soTemp.getProperty(14).toString().equals("anyType{}")){
				thuocDTO.setLIEULUONG(sChoCapNhat);
			}else{
				thuocDTO.setLIEULUONG(soTemp.getProperty(14).toString());
			}
			if(soTemp.getProperty(15).toString().equals("anyType{}")){
				thuocDTO.setBAOQUAN(sChoCapNhat);
			}else{
				thuocDTO.setBAOQUAN(soTemp.getProperty(15).toString());
			}
			if(soTemp.getProperty(16).toString().equals("anyType{}")){
				thuocDTO.setNHANBIET(sChoCapNhat);
			}else{
				thuocDTO.setNHANBIET(soTemp.getProperty(16).toString());
			}	
			//save thuocDTO into Db if not exist
			ThuocBUS thuocBUS = new ThuocBUS();
			boolean bCheckExistAndInsert = thuocBUS.checkThuocExistAndInsert(thuocDTO, this);
			if(bCheckExistAndInsert)
			{
				// thuocDTO does not exist and had been inserted
			}
			else
			{
				// thuocDTO exist
				// thuocDTO had not been inserted
				//CatchError("Có lỗi xảy ra");
			}
			// add thuocDTO to lstThuoc
			lstThuoc[i] = thuocDTO;
		}
		return lstThuoc;
	}

	public void showSearchResultToListView(List<ThuocDTO> lstThuoc)
	{
		// Use the SimpleCursorAdapter to show the elements in a ListView
		ArrayList<String> lstTenThuoc = new ArrayList<String>();
		for(int i = 0; i < lstThuoc.size(); i++)
		{
			ThuocDTO thuoc = lstThuoc.get(i);
			lstTenThuoc.add(thuoc.getTENTHUOC());
		}

		String[] tenThuocs = lstTenThuoc.toArray(new String[0]);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listview_item, tenThuocs);
		myList.setAdapter(adapter);
	}

	private void CatchError(String Exception)
	{
		Dialog diag = new Dialog(this);
		diag.setTitle("Thông báo MHS");
		TextView txt = new TextView(this);
		txt.setText(Exception);
		diag.setContentView(txt);
		diag.show();
	}


	private void loadSpinnerSearchType() 
	{
		String typeSearch[] = {"Tên thuốc", "Thành phần", "Chỉ định", "Công ty sản xuất", "Số đăng ký"};
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, typeSearch);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinSearchType.setAdapter(adapter);



	}
}

